﻿//*********************************************************

//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Microsoft Public License.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

//*********************************************************

namespace ODataTestGen.Wizard
{
    using System;
    using System.Data.Metadata.Edm;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using Microsoft.Win32;
    using ODataTestGen.Data;
    using ODataTestGen.OData;
    using System.Xml.Linq;

    /// <summary>
    /// Interaction logic for Page1.xaml
    /// </summary>
    public partial class StartPage : Page
    {
        public TestGenerationConfiguration Configuration;

        public StartPage()
        {
            this.InitializeComponent();
            this.WindowHeight = 500;
            this.WindowWidth = 950;

        }

        private void EnableDisableControls()
        {
            if (!IsLoaded)
            {
                return;
            }

            bool ok = true;

            if (string.IsNullOrEmpty(this.textBoxServiceUri.Text))
            {
                ok = false;
            }

            if (true.Equals(this.radioButtonLoadMetadataFromFile.IsChecked))
            {
                this.textBoxEdmxFileName.IsEnabled = true;
                this.buttonBrowseEdmx.IsEnabled = true;
                if (string.IsNullOrEmpty(this.textBoxEdmxFileName.Text))
                {
                    ok = false;
                }
                else
                    ok = true;
            }
            else
            {
                this.textBoxEdmxFileName.IsEnabled = false;
                this.buttonBrowseEdmx.IsEnabled = false;
            }

            this.buttonNext.IsEnabled = ok;
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            this.textBoxServiceUri.Text = "http://api.visitmix.com/OData.svc/"; 

            this.Configuration = new TestGenerationConfiguration();
            this.buttonNext.IsEnabled = true;

            this.EnableDisableControls();
        }

        /// <summary>
        /// The function uses EdmxParser to parse the metadata from a service uri or local file, saves 
        /// it as a temporary file named "temp.edmx" under your TextTemplating directory. 
        /// Exceptions may be thrown out in following situaions:
        /// 1. The uri is not working;
        /// 2. The local file doesn't exist;
        /// 3. The namespace of edmx schema doesn't pass the verification process of EdmItemCollection
        /// 4. The user doesn't have TextTemplating installed on local machine (It should be already there if VS 2008/2010 is installed)
        ///    or the directory is not 
        ///    %ProgramFiles%\Common Files\microsoft shared\TextTemplating\[version number]\TextTransform.exe. (x86)
        ///    %ProgramFiles(x86)%\Common Files\microsoft shared\TextTemplating\[version number]\TextTransform.exe. (x64)   
        /// 5. The program doesn't have a WRITE privilege under the directory.
        /// </summary>

        private void buttonNext_Click(object sender, RoutedEventArgs e)
        {
            this.buttonNext.IsEnabled = false;
            bool loadFromServer = this.radioButtonDownloadMetadata.IsChecked.Value;
            string metadata;

            if(this.radioButtonDownloadMetadata.IsChecked.Value)
                this.Configuration.BaseUri = new Uri(this.textBoxServiceUri.Text);
            if (loadFromServer)
            {
                metadata = this.textBoxServiceUri.Text;
            }
            else
            {
                metadata = this.textBoxEdmxFileName.Text;
            }
            if ((!loadFromServer) && (!File.Exists(metadata)))
            {
                MessageBox.Show("The local edmx file doesn't exist");
                return;
            }
            EdmxParser parser = new EdmxParser();

            try
            {
                XElement svcDoc = XElement.Load(metadata);
            }
            catch (WebException ex)
            {
                MessageBox.Show("Error: Please check the service uri.\n\n" + ex);
                return;
            }

            Action a = () =>
                {
                    try
                    {
                        if (loadFromServer)
                        {
                            this.Configuration.edmxElement = parser.ParseEdmxFromService(metadata);
                        }
                        else
                        {
                            this.Configuration.edmxElement = parser.ParseEdmxFromFile(metadata);
                        }
                        this.Configuration.Metadata = parser.Metadata;
                        Dispatcher.BeginInvoke((Action)MetadataLoaded);
                    }
                    catch (WebException ex)
                    {
                                               
                        MessageBox.Show("Error: Please check the following uri: " + metadata + "/$metadata" + ".\nThe validator doesn't support nested service doc currently. If you are entering a nested service doc please specify a serviec doc with feed.\n" + ex);
                        return;
                    }
                    catch (NullReferenceException ex)
                    {
                        MessageBox.Show("Error: Please check the format of the edmx metadata.\n\n" + ex);
                        return;
                    }
                    catch (DirectoryNotFoundException ex)
                    {
                        MessageBox.Show("Error: Please check the directory of TextTemplating.\n\n" + ex);
                        return;
                    }
                };
            a.BeginInvoke(null, null);
        }

        private void MetadataLoaded()
        {
            if (this.radioButtonDownloadMetadata.IsChecked.Value)
            {
                this.Configuration.defaultServiceRoot = this.textBoxServiceUri.Text;
                if (!this.Configuration.defaultServiceRoot.EndsWith("/"))
                    this.Configuration.defaultServiceRoot += "/";
            }
            this.progressBarLoading.Visibility = Visibility.Hidden;
            var container = this.Configuration.Metadata.GetItems<EntityContainer>().Single();
            var sets = container.BaseEntitySets.OfType<EntitySet>().Select(c => new EntitySetConfiguration
            {
                Name = c.Name,
                GetTest = true,
                DeleteTest = true,
                PutTest = true,
                PostTest = true,
            });

            this.Configuration.Entities.AddRange(sets);

            this.NavigationService.Navigate(new SelectEntitySets { Configuration = this.Configuration });
        }

        private void radioButtonDownloadMetadata_Checked(object sender, RoutedEventArgs e)
        {
            this.EnableDisableControls();
        }

        private void radioButtonLoadMetadataFromFile_Checked(object sender, RoutedEventArgs e)
        {
            this.EnableDisableControls();
        }

        private void textBoxServiceUri_TextChanged(object sender, TextChangedEventArgs e)
        {
            this.EnableDisableControls();
        }

        private void buttonBrowseEdmx_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;
            dialog.Filter = "Edmx File(*.edmx)|*.edmx|All Files(*.*)|*.*";
            Nullable<bool> result = dialog.ShowDialog();
            if (result == true)
            {
                this.textBoxEdmxFileName.Text = dialog.FileName;
            }
            this.EnableDisableControls();
        }

        private void textBoxEdmxFileName_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!this.radioButtonDownloadMetadata.IsChecked.Value)
            {
                if (this.textBoxEdmxFileName.Text.Length > 0)
                    this.buttonNext.IsEnabled = true;
                else
                    this.buttonNext.IsEnabled = false;
            }
        }

        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            ((Window)this.Parent).Close();
        }
    }
}